﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using nSL.Libs;
using nSL.Config;
using DevExpress.Xpf.LayoutControl;
using System.Data;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace nSL.UC
{
    /// <summary>
    /// Interaction logic for Lecture.xaml
    /// </summary>
    public partial class Lecture : UserControl
    {
        public Lecture()
        {
            InitializeComponent();
        }


        [DllImport("User32", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern int BringWindowToTop(IntPtr hwnd);

        private Common.LECTURE_INFO _lectureInfo;
        public Common.LECTURE_INFO LectureInfo
        {
            get { return _lectureInfo; }
            set { _lectureInfo = value; }
        }
        List<string> generatedGroups = new List<string>();

        private void ApplicationTile(TileLayoutControl tileLayout)
        {
            #region Tile user
            string userName = Common.USER_DATA.Tables[0].Rows[0][1].ToString();
            string userCourse = Common.USER_DATA.Tables[0].Rows[0][2].ToString();
            string userInfo = string.Format("{0}\n{1}", userName, userCourse);

            Tile infoTile = new Tile() { Header = userInfo, Name = "tInfo", Size = TileSize.Large };
            string navGroup = "Application";
            infoTile.SetValue(TileLayoutControl.GroupHeaderProperty, navGroup);

            #region add image to tile
            Image tileImag = new Image();
            BitmapImage imag = new BitmapImage();
            Grid gr = new Grid();
            imag.BeginInit();
            imag.UriSource = new Uri("pack://application:,,,/nSL;component/Images/Icons/info-7-128.png");
            imag.EndInit();
            tileImag.Source = imag;
            tileImag.Stretch = Stretch.None;
            tileImag.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            tileImag.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            infoTile.Content = tileImag;
            #endregion

            if (!generatedGroups.Contains(navGroup))
            {
                infoTile.SetValue(TileLayoutControl.IsFlowBreakProperty, true);
                generatedGroups.Add(navGroup);
            }
            tileLayout.Children.Add(infoTile);
            RegisterName(infoTile.Name, infoTile);
            #endregion

            #region Tile Back
            Tile backTile = new Tile() { Header = "", Name = "tBack", Size = TileSize.Small };
            backTile.SetValue(TileLayoutControl.GroupHeaderProperty, navGroup);
            backTile.Click += new EventHandler(backTile_Click);

            #region add image to tile
            Image tileBackImag = new Image();
            BitmapImage Bimag = new BitmapImage();
            Bimag.BeginInit();
            Bimag.UriSource = new Uri("pack://application:,,,/nSL;component/Images/Icons/back-128.png");
            Bimag.EndInit();
            tileBackImag.Source = Bimag;
            tileBackImag.Stretch = Stretch.None;
            backTile.Content = tileBackImag;
            #endregion

            if (!generatedGroups.Contains(navGroup))
            {
                backTile.SetValue(TileLayoutControl.IsFlowBreakProperty, true);
                generatedGroups.Add(navGroup);
            }
            tileLayout.Children.Add(backTile);
            RegisterName(backTile.Name, backTile);
            #endregion

            #region Tile exit
            Tile exitTile = new Tile() { Header = "", Name = "tExit", Size = TileSize.Small };
            exitTile.SetValue(TileLayoutControl.GroupHeaderProperty, navGroup);
            exitTile.Click += new EventHandler(exitTile_Click);

            #region add image to tile
            Image tileExitImag = new Image();
            BitmapImage imagExit = new BitmapImage();
            imagExit.BeginInit();
            imagExit.UriSource = new Uri("pack://application:,,,/nSL;component/Images/Icons/exit-4-128.png");
            imagExit.EndInit();
            tileExitImag.Source = imagExit;
            tileExitImag.Stretch = Stretch.None;
            exitTile.Content = tileExitImag;
            #endregion

            if (!generatedGroups.Contains(navGroup))
            {
                exitTile.SetValue(TileLayoutControl.IsFlowBreakProperty, true);
                generatedGroups.Add(navGroup);
            }
            tileLayout.Children.Add(exitTile);
            RegisterName(exitTile.Name, exitTile);
            #endregion
        }

        private void TileGenerater(Common.LECTURE_FILE_INFO infoTag, string lectureName)
        {
            try
            {
                Random ed = new Random();
                int rdName = ed.Next(20001, 99999);
                string eman = "A" + rdName + "A";

                Tile newTile = new Tile()
                {
                    //Header = infoTag.file_desp + "" + infoTag.file_type,
                    Header = infoTag.file_type,
                    Name = eman + infoTag.file_id,
                    Size = TileSize.Large,
                    FontSize = 16.0,
                    Tag = infoTag,
                    HorizontalHeaderAlignment = System.Windows.HorizontalAlignment.Right,
                    VerticalHeaderAlignment = System.Windows.VerticalAlignment.Bottom
                };
                string a = LectureInfo.course_id;
                string b = LectureInfo.lecture_id;
                string c = infoTag.file_desp;

                #region calculate file name
                string imgURL = "http://";
                imgURL += Config.Configurations.Server;
                imgURL += "/eThumbs/";
                imgURL += LectureInfo.course_id;
                imgURL += "/";
                imgURL += infoTag.file_desp + ".jpg";
                string hashFile = EncryptHelper.CalculateSHA1(imgURL);
                #endregion

                #region set tile background
                Image finalImage = new Image();
                BitmapImage img = Images.FromFile(Common.TEMP_PATH + hashFile + ".jpg");
                if (img != null)
                {
                    finalImage.Source = img;
                    finalImage.Stretch = Stretch.Fill;
                    newTile.Background = new ImageBrush(img);
                }
                #endregion

                #region stack panel
                StackPanel stack = new StackPanel();
                stack.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                stack.Height = 35;
                stack.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#8E313131"));
                TextBlock txtBlock = new TextBlock();
                txtBlock.TextAlignment = TextAlignment.Right;
                txtBlock.Margin = new Thickness(0, 10, 10, 0);
                txtBlock.Text = infoTag.file_desp;
                txtBlock.Foreground = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFFFFFFF"));
                stack.Children.Add(txtBlock);
                #endregion

                newTile.Content = stack;

                newTile.SetValue(TileLayoutControl.GroupHeaderProperty, lectureName);
                newTile.Click += new EventHandler(newTile_Click);

                if (!generatedGroups.Contains(lectureName))
                {
                    newTile.SetValue(TileLayoutControl.IsFlowBreakProperty, true);
                    generatedGroups.Add(lectureName);
                }
                tileLayoutControl1.Children.Add(newTile);
                RegisterName(newTile.Name, newTile);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private BitmapImage getImageURL(string url)
        {
            try
            {
                var image = new BitmapImage();
                int BytesToRead = 100;

                WebRequest request = WebRequest.Create(new Uri(url, UriKind.Absolute));
                request.Timeout = -1;
                WebResponse response = request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                BinaryReader reader = new BinaryReader(responseStream);
                MemoryStream memoryStream = new MemoryStream();

                byte[] bytebuffer = new byte[BytesToRead];
                int bytesRead = reader.Read(bytebuffer, 0, BytesToRead);

                while (bytesRead > 0)
                {
                    memoryStream.Write(bytebuffer, 0, bytesRead);
                    bytesRead = reader.Read(bytebuffer, 0, BytesToRead);
                }

                image.BeginInit();
                memoryStream.Seek(0, SeekOrigin.Begin);

                image.StreamSource = memoryStream;
                image.EndInit();

                return image;
            }
            catch
            {
                return null;
            }
        }

        private void GernerateAll()
        {
            #region Clear old tile
            foreach (Tile tile in tileLayoutControl1.Children.OfType<Tile>())
                UnregisterName(tile.Name);
            tileLayoutControl1.Children.Clear();
            #endregion
            string lectureID = LectureInfo.lecture_id;
            DataTable dtLectureFile = Common.COURSE_FILE.Tables[0];
            DataRow[] rows = dtLectureFile.Select("LectureID=" + lectureID);
            foreach (DataRow dr in rows)
            {
                Common.LECTURE_FILE_INFO fileInfo = new Common.LECTURE_FILE_INFO();
                fileInfo.lecture_id = dr["LectureID"].ToString();
                fileInfo.file_id = dr["Vdoid"].ToString();
                fileInfo.file_desp = dr["VdoName"].ToString();
                fileInfo.file_type = dr["TypeFile"].ToString();
                TileGenerater(fileInfo, LectureInfo.lecture_name);
            }
            ApplicationTile(tileLayoutControl1);
        }

        public void IsPDF(string uri, Common.LECTURE_FILE_INFO info)
        {
            string argv = LectureInfo.course_id + "/" + info.file_desp + info.file_type;
            string fileURL = @"http://" + Config.Configurations.Server + "/eThumbs/" + argv;

            string encryp = EncryptHelper.CalculateSHA1(fileURL);

            UC.PDFViewer pdfView = new PDFViewer();
            pdfView.PdfPath = uri;
            WpfPageTransitions.PageTransition transition = new WpfPageTransitions.PageTransition();
            transition.TransitionType = WpfPageTransitions.PageTransitionType.Slide;
            transition.ShowPage(pdfView);
            Window.GetWindow(this).Content = transition;
        }

        public void IsVDO(string uri)
        {
            UC.Video vCon = new Video();
            vCon.TagInfo = LectureInfo;
            vCon.FileURI = uri;
            WpfPageTransitions.PageTransition transition = new WpfPageTransitions.PageTransition();
            transition.TransitionType = WpfPageTransitions.PageTransitionType.Slide;
            transition.ShowPage(vCon);
            Window.GetWindow(this).Content = transition;
        }

        public void IsExecute(string uri, Common.LECTURE_FILE_INFO info,Tile tClick)
        {
            string argv = LectureInfo.course_id + "/" + info.file_desp + info.file_type;
            string fileURL = @"http://" + Config.Configurations.Server + "/eThumbs/" + argv;
            string encryp = EncryptHelper.CalculateSHA1(fileURL);



            string docPath = Common.TEMP_PATH + encryp + info.file_type;
            Process docProc = new Process();
            docProc.StartInfo.FileName = docPath;
            docProc.Start();
            docProc.WaitForExit();
        }

        public void IsDoc(string uri,Common.LECTURE_FILE_INFO info)
        {
            string argv = LectureInfo.course_id + "/" + info.file_desp + info.file_type;
            string fileURL = @"http://" + Config.Configurations.Server + "/eThumbs/" + argv;

            string encryp = EncryptHelper.CalculateSHA1(fileURL);

            string appPath = nSLLibs.MSOfficePath(nSLLibs.MSOffice.Word);
            string docPath = Common.TEMP_PATH + encryp + info.file_type;
            Process docProc = new Process();
            docProc.StartInfo.FileName = appPath;
            docProc.StartInfo.Arguments = "/f " + docPath;
            docProc.Start();
            docProc.WaitForExit();
        }

        public void IsPPT(string uri, Common.LECTURE_FILE_INFO info)
        {
            string argv = LectureInfo.course_id + "/" + info.file_desp + info.file_type;
            string fileURL = @"http://" + Config.Configurations.Server + "/eThumbs/" + argv;

            string encryp = EncryptHelper.CalculateSHA1(fileURL);

            string appPath = nSLLibs.MSOfficePath(nSLLibs.MSOffice.Powerpoint);
            string docPath = Common.TEMP_PATH + encryp + info.file_type;
            Process docProc = new Process();
            docProc.StartInfo.FileName = appPath;
            docProc.StartInfo.Arguments = "/f " + docPath;
            docProc.Start();
            docProc.WaitForExit();
        }

        void newTile_Click(object sender, EventArgs e)
        {
            Tile currTile = (Tile)sender;
            Console.WriteLine(currTile.Name);
            Common.LECTURE_FILE_INFO currInfo = (Common.LECTURE_FILE_INFO)currTile.Tag;
            //open vdo file
            //mms://NEXTWAVE-7403F4/nSelf/123/14-02.wmv
            string argv = LectureInfo.course_id + "/" + currInfo.file_desp + currInfo.file_type;
            string fileURL = @"http://" + Config.Configurations.Server + "/eThumbs/" + argv;
            string fileURI = Config.Configurations._protocal + Config.Configurations.Server + "/" + Config.Configurations.PublishPoint + "/" + LectureInfo.course_id + "/" + currInfo.file_desp + ".wmv";

            switch (currInfo.file_type)
            {
                case ".pdf": IsPDF(fileURL, currInfo);
                    break;
                case ".doc":
                case ".Doc":
                case ".docx":
                case ".Docx": IsDoc(fileURL, currInfo);
                    break;
                case ".ppt": IsPPT(fileURL, currInfo);
                    break;
                case ".exe": IsExecute(fileURL, currInfo,currTile);
                    break;
                default: IsVDO(fileURL);
                    break;
            }
            Common.lecture_file_info = currInfo;
        }

        void backTile_Click(object sender, EventArgs e)
        {
            Array tType = Enum.GetValues(typeof(WpfPageTransitions.PageTransitionType));
            Random rd = new Random();
            int inrd = rd.Next(0, tType.Length - 1);
            UC.Course course = new Course();
            WpfPageTransitions.PageTransition transition = new WpfPageTransitions.PageTransition();
            transition.TransitionType = (WpfPageTransitions.PageTransitionType)tType.GetValue(inrd);
            transition.ShowPage(course);
            Window.GetWindow(this).Content = transition;
        }

        void exitTile_Click(object sender, EventArgs e)
        {
            if (Message.Confirm(cString.ID("logout")))
            {
                UC.WhoRU log = new WhoRU();
                WpfPageTransitions.PageTransition transition = new WpfPageTransitions.PageTransition();
                transition.TransitionType = WpfPageTransitions.PageTransitionType.Slide;
                transition.ShowPage(log);
                Window.GetWindow(this).Content = transition;
            }
            //do exit here
            //throw new NotImplementedException();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            GernerateAll();
        }

    }
}
